/**
 * @author Fang Lu, fanglupku@gmail.com
 * 2011-4-13
 */
package dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashSet;

public class ErrorPageRecorder {
	private HashSet<String> errorURLSet = new HashSet<String>();
	private BufferedWriter bw;
	public ErrorPageRecorder(String filename, String encode){
		File file = new File(filename);
		try {
			if (!file.exists()){
				file.createNewFile();
			}
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = null;
			if (encode == null){
				isr = new InputStreamReader(fis);
			}else{
				isr = new InputStreamReader(fis, encode);
			}
			BufferedReader br = new BufferedReader(isr);
			String oneLine = br.readLine();
			while (oneLine != null){
				errorURLSet.add(oneLine.trim());
				oneLine = br.readLine();
			}
			br.close();
			isr.close();
			fis.close();
			
			if (encode == null){
				bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
			}else{
				bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encode));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public HashSet<String> getErrorURLSet() {
		return errorURLSet;
	}
	public boolean addErrorPage(String errorPage){
		try {
			if (!errorURLSet.contains(errorPage)){
				bw.write(errorPage);
				bw.write("\n");
				bw.flush();
				errorURLSet.add(errorPage);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public boolean addErrorPageList(ArrayList<String> errorPageList){
		try {
			for (int i=0; i<errorPageList.size(); ++i){
				if (!errorURLSet.contains(errorPageList.get(i))){
					bw.write(errorPageList.get(i));
					bw.write("\n");
					errorURLSet.add(errorPageList.get(i));
				}
			}
			bw.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public void close(){
		try {
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
